import axios from "axios";
import { EventSourcePolyfill } from "event-source-polyfill";

/**
 * 发送聊天消息（流式响应）
 * @param message 用户发送的消息内容
 * @returns EventSource实例
 */
const token = localStorage.getItem("token"); // 从localStorage获取token
const baseURL = import.meta.env.VITE_API_BASE_URL + import.meta.env.VITE_GLOB_API_URL
export const sendChatStream = (message: string): EventSource => {
  return new EventSourcePolyfill(
    `${baseURL}/file/chat-stream?message=${encodeURIComponent(message)}`,
    { headers: { 'Accept': 'text/event-stream' ,
      'Authorization': `Bearer ${token}` // 添加Bearer Token认证
    } }
  );
};

/**
 * 上传文件到服务器
 * @param file 要上传的文件对象
 * @returns 上传结果响应
 */
export const uploadFileToServer = (file: File) => {
  const formData = new FormData();
  formData.append('file', file);
  
  return axios.post(`${baseURL}/file/upload`, formData, {
    headers: { 'Content-Type': 'multipart/form-data' ,
      'Authorization': `Bearer ${token}` // 添加Bearer Token认证
    }
  });
};

/**
 * 分析文档内容（流式响应）
 * @param objectName 文档对象名称
 * @param request 用户请求内容
 * @returns EventSource实例
 */
export const analyzeDocumentStream = (objectName: string, request: string): EventSource => {
  return new EventSourcePolyfill(
    `${baseURL}/file/stream-process?objectName=${encodeURIComponent(objectName)}&request=${encodeURIComponent(request)}`,
    { headers: { 'Accept': 'text/event-stream' ,
      'Authorization': `Bearer ${token}` // 添加Bearer Token认证
    } }
  );
};

// 导出ChatMessage类型
export interface ChatMessage {
  role: 'user' | 'assistant';
  content?: string;
  type: 'text' | 'file';
  time: Date;
  loading?: boolean;
  fileName?: string;
  objectName?: string;
  analysis?: boolean;
  error?: boolean; // 添加error属性
}